package cn.cheqi.recovery.api.utils;

import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class AliyunOssUtil {
    private static final Logger log = LoggerFactory.getLogger(AliyunOssUtil.class);

    @Value("${aliyun.oss.ImgUrlPrefix}")
    private String ImgUrlPrefix;

    @Value("${aliyun.oss.EndPoint}")
    private String EndPoint;

    @Value("${aliyun.oss.AccessKeyId}")
    private String AccessKeyId;

    @Value("${aliyun.oss.AccessKeySecret}")
    private String AccessKeySecret;

    @Value("${aliyun.oss.BucketName}")
    private String BucketName;


    /**
     * 文件流上传
     * @param file 文件
     * @param fileName  文件名
     * @return
     */
    public String uploadInputStream(InputStream file, String fileName) {

        OSSClient ossClient = new OSSClient(EndPoint, new DefaultCredentialProvider(AccessKeyId, AccessKeySecret), null);
        try {
            ossClient.putObject(BucketName, fileName, file);
            ossClient.shutdown();
            return ImgUrlPrefix + "/" + fileName;
        } catch (Exception ex) {
            throw new RuntimeException("上传文件出错，请检查配置" + ex.toString());
        }
    }

    /**
     * 生成新的文件名
     * @param fileName
     * @param folderType 设置是哪种类型的文件夹,业主或者员工或者社区
     * @return
     */
    public String reName(String fileName,String folderType) {
        //获取文件后缀
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //根据年月日生成文件夹名字
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        //年月日文件夹文字
        String dateFolder = sdf.format(new Date());
        //生成UUID文件前缀名
        String UUIDname = IdUtil.simpleUUID().toUpperCase().replace("-", "");
        //生成新的文件名
        String newFileName =  folderType + dateFolder + "/" + UUIDname + suffixName;
        //返回新生成的文件名
        return newFileName;
    }
}
